﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RBS.Core.Extension
{
    /// <summary>
    /// Object扩展方法
    /// </summary>
    public static class ObjectExtension
    {
        public static Int32 ToInt32(this Object obj) {
            Int32 int_val = 0;
            if (Int32.TryParse(obj.ToString(), out int_val))
                return int_val;
            return 0;
            //throw new Exception("Can not convert to int32 type");
        }

        public static Int64 ToInt64(this Object obj)
        {
            Int64 int_val = 0;
            if (Int64.TryParse(obj.ToString(), out int_val))
                return int_val;

            return 0;
            //throw new Exception("Can not convert to int64 type");
        }

        public static Decimal ToDecimal(this Object obj) {
            decimal d_val = 0;
            if (decimal.TryParse(obj.ToString(), out d_val))
                return d_val;
            return 0m;
            //throw new Exception("Can not convert to decimal type");
        }

        public static DateTime ToDateTime(this Object obj) {
            DateTime dt_val = DateTime.MinValue;
            if (DateTime.TryParse(obj.ToString(), out dt_val))
                return dt_val;

            return DateTime.MinValue;
            //throw new Exception("Can not convert to DateTime type");
        }

        public static T ToEnum<T>(this Object obj) where T:struct
        {
            T t_val = default(T);
            if (Enum.TryParse<T>(obj.ToString(),true, out t_val))
                return t_val;

            return default(T);
            //throw new Exception(String.Format("Can not Convert to the type {0} ", typeof(T).ToString()));
        }
    }
}
